extends Control

@onready var dir_center_marker: Marker2D = $MobileControl/DirectionContainer/DirectionButton/DirCenterMarker
@onready var fire_marker: Marker2D = $MobileControl/FilreContainer/FireTextureButton/FireMarker
@onready var direction_button: TextureRect = $MobileControl/DirectionContainer/DirectionButton
@onready var fire_texture_button: TextureRect = $MobileControl/FilreContainer/FireTextureButton
@onready var players_list_container: HBoxContainer = $PlayersListContainer
@onready var level_name: Label = $LevelContainer/HBoxContainer/LevelName


var player_info_panel_tscn := preload("res://entity/ui/player_info_panel.tscn")

var dir_touch_index := -1
var fire_touch_index := -1

func _ready() -> void:
	SignalManager.player_update.connect(player_update)
	SignalManager.level_update.connect(level_update)


func level_update(level: int) -> void:
	level_name.text = str(level + 1)


func player_update() -> void:
	var players := get_tree().get_nodes_in_group("player")
	for i in players.size():
		var panel: PanelContainer
		if players_list_container.has_node(str(i)):
			panel = players_list_container.get_node(str(i))
		else:
			panel = player_info_panel_tscn.instantiate()
			panel.name = str(i)
			players_list_container.add_child(panel)
		panel.get_node("PlayerInfoContainer/PlauerName").text = "P" + str(i + 1)
		panel.get_node("PlayerInfoContainer/HBoxContainer/Damge").text = str(players[i].damage)
		panel.get_node("PlayerInfoContainer/HBoxContainer/FireRate").text = str(players[i].fire_rate)
		panel.get_node("PlayerInfoContainer/HBoxContainer2/Speed").text = str(players[i].speed)
		panel.get_node("PlayerInfoContainer/HBoxContainer2/ShellSpeed").text = str(players[i].shell_speed)
		panel.get_node("PlayerInfoContainer/HBoxContainer3/Health").text = str(players[i].health)
		panel.get_node("PlayerInfoContainer/HBoxContainer3/MaxHealth").text = str(players[i].max_health)



func _unhandled_input(event: InputEvent) -> void:
	var player: Player = Game.get_current_player()
	if event is InputEventScreenTouch:
		if event.pressed:
			if dir_center_marker.global_position.distance_to(event.position) < 170.0:
				dir_touch_index = event.index
			if fire_marker.global_position.distance_to(event.position) < 125.0 and player and player.fire_rate_timer.time_left == 0:
				player.make_fire()
		else:
			if dir_touch_index == event.index: 
				dir_touch_index = -1
				if player:
					player.get_node("PlayerInput").touch_vector = Vector2.ZERO
			if fire_touch_index == event.index: fire_touch_index = -1
	elif event is InputEventScreenDrag:
		if dir_touch_index == event.index:
			if player:
				player.get_node("PlayerInput").touch_vector = dir_center_marker.global_position.direction_to(event.position)





func _on_game_set_button_button_down() -> void:
	Game.set_state.rpc(Game.GameState.GAMING_MENU)
